package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eva.epc.common.util.CommonUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.service.IZhikeUsersService;
import com.mdd.admin.validate.ZhikeUsersCreateValidate;
import com.mdd.admin.validate.ZhikeUsersSearchValidate;
import com.mdd.admin.validate.user.UserUpdateValidate;
import com.mdd.admin.vo.ZhikeUsersListedVo;
import com.mdd.admin.vo.ZhikeUsersDetailVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.ZhikeUsers;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.ZhikeUsersMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 用户实现类
 * @author LikeAdmin
 */
@Service
public class ZhikeUsersServiceImpl implements IZhikeUsersService {

    @Resource
    ZhikeUsersMapper zhikeUsersMapper;

    /**
     * 用户列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<ZhikeUsersListedVo>
     */
    @Override
    public PageResult<ZhikeUsersListedVo> list(PageValidate pageValidate, ZhikeUsersSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<ZhikeUsers> queryWrapper = new QueryWrapper<>();
        //合并查询
        if (searchValidate.getUserInfo() != null){
            queryWrapper
                    .eq("user_uid", searchValidate.getUserInfo())
                    .or()
                    .like("nickname", searchValidate.getUserInfo())
                    .or()
                    .like("phone", searchValidate.getUserInfo());
        }
        queryWrapper.orderByDesc("user_uid");

        zhikeUsersMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:userUid@user_uid:long",
            "=:accountNumber@account_number:str",
            "=:phone:str",
            "like:nickname:str",
            "=:userSex@user_sex:long",
            "=:registerIp@register_ip:str",
            "=:registerTime@register_time:str",
            "=:isOnline@is_online:long",
            "=:accountStatus@account_status:str",
        });

        IPage<ZhikeUsers> iPage = zhikeUsersMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<ZhikeUsersListedVo> list = new LinkedList<>();
        for(ZhikeUsers item : iPage.getRecords()) {
            ZhikeUsersListedVo vo = new ZhikeUsersListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 用户详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return ZhikeUsers
     */
    @Override
    public ZhikeUsersDetailVo detail(Integer id) {
        ZhikeUsers model = zhikeUsersMapper.selectOne(
                new QueryWrapper<ZhikeUsers>()
                    .eq("user_uid", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        ZhikeUsersDetailVo vo = new ZhikeUsersDetailVo();
        BeanUtils.copyProperties(model, vo);
        if (model.getUserSex() != null && model.getUserSex() == 1){
            vo.setUserSex("男");
        }else{
            vo.setUserSex("女");
        }
        return vo;
    }

    /**
     * 用户新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(ZhikeUsersCreateValidate createValidate) {
        ZhikeUsers model = new ZhikeUsers();
        model.setAccountNumber(createValidate.getAccountNumber());
        model.setPhone(createValidate.getPhone());
        model.setNickname(createValidate.getNickname());
        model.setUserSex(createValidate.getUserSex());
        model.setUserAvatarFileName(createValidate.getUserAvatarFileName());
        model.setAccountStatus(createValidate.getAccountStatus());
        String encyptPassword = CommonUtils.encyptPassword(createValidate.getUserPsw(), "");
        model.setUserPsw(encyptPassword);
        model.setRegisterTime(new Date());
        zhikeUsersMapper.insert(model);
    }

    /**
     * 用户编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(UserUpdateValidate updateValidate) {
        String field = updateValidate.getField();
        String value = updateValidate.getValue();

        ZhikeUsers user = zhikeUsersMapper.selectOne(
                new QueryWrapper<ZhikeUsers>()
                        .eq("user_uid",  updateValidate.getId())
                        .eq("deleted",  0)
                        .last("limit 1"));

        com.baomidou.mybatisplus.core.toolkit.Assert.notNull(user, "用户不存在!");

        switch (field) {
            case "nickname":
                com.baomidou.mybatisplus.core.toolkit.Assert.isTrue(value.length() <= 32,"真实姓名不能超过32个字符");
                user.setNickname(value);
                break;
            case "userSex":
                user.setUserSex(Long.valueOf(value));
                break;
            case "userPsw":
                String encyptPassword = CommonUtils.encyptPassword(value, "");
                user.setUserPsw(encyptPassword);
                break;
            case "phone":
                if (!Pattern.matches("^[1][3-9][0-9]{9}$", value)) {
                    throw new OperateException("手机号格式不正确!");
                }
                user.setPhone(value);
                break;
            default:
                throw new OperateException("不被支持的字段类型!");
        }

        zhikeUsersMapper.updateById(user);
    }

    /**
     * 用户删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        ZhikeUsers model = zhikeUsersMapper.selectOne(
                new QueryWrapper<ZhikeUsers>()
                    .eq("user_uid", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        zhikeUsersMapper.delete(new QueryWrapper<ZhikeUsers>().eq("user_uid", id));
    }

    @Override
    public void resetPassword(Integer userUid) {
        ZhikeUsers model = zhikeUsersMapper.selectOne(
                new QueryWrapper<ZhikeUsers>()
                        .eq("user_uid", userUid)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        //#123456
        model.setUserPsw("96e79218965eb72c92a549dd5a330112");

        zhikeUsersMapper.updateById(model);
    }

}
